package cn.edu.ujs.coor.util;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.edu.ujs.coor.common.exception.CoorException;
import org.apache.http.NameValuePair;
import org.apache.poi.ss.usermodel.Workbook;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Excel导出工具类
 *
 * @author 柳曾雄
 * @date 2018-08-05
 */
public class ExcelUnit {

    /**
     * excel导出
     * @return
     */
    public static ByteArrayOutputStream export (List<NameValuePair> fields, List<Map<String, Object>> list) {
        ByteArrayOutputStream baos = null;
        List<ExcelExportEntity> entity = null;
        try {
            baos = new ByteArrayOutputStream();
            entity = new ArrayList<>();
            for (NameValuePair pair : fields) {
                ExcelExportEntity exportEntity = new ExcelExportEntity(pair.getName(), pair.getValue());
                exportEntity.setWidth(30);
                entity.add(exportEntity);
            }
            Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(null, "Sheet1"), entity,
                    list);
            workbook.write(baos);
        } catch (Exception e) {
            throw new CoorException("数据导出失败");
        }
        return baos;
    }
}
